package com.cx.base.day13_io.io_02_fileStream;

import java.io.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.util.Properties;
import java.util.Set;

/**
 * @author shkstart
 * @date 8/1/2019 - 3:15 PM
 */
public class FileReader2WriterTest {

    public static void main(String[] args) throws IOException {
        baseCharacter();
        baseCharacterArray();
    }

    public static String properties() throws IOException {
        return System.getProperty("file.separator");
    }

    //    基于字符的读写流
    public static void baseCharacter() throws IOException {
        FileWriter fileWriter = null;
        FileReader fileReader = null;
        String separator = properties();
        File file1 = new File("." + separator + "test0.txt");
        File file2 = new File("." + separator + "test3.txt");
        file1.createNewFile();
        file2.createNewFile();
        int unicodeOfChar;
        long start = 0;
        try {
            fileReader = new FileReader(file1);
            fileWriter = new FileWriter(file2, true);
            start = System.currentTimeMillis();
            while ((unicodeOfChar = fileReader.read()) != -1) {
                fileWriter.write(unicodeOfChar);
//                fileWriter.flush();
            }
            System.out.println("复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
            if (fileReader != null) {
                fileReader.close();
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    }

    //    基于字符的读写流
    public static void baseCharacterArray() throws IOException {
        FileWriter fileWriter = null;
        FileReader fileReader = null;
        String separator = properties();
        File file1 = new File("." + separator + "test0.txt");
        File file2 = new File("." + separator + "test4.txt");
        file1.createNewFile();
        file2.createNewFile();
        char[] chars = new char[1024];
        int charsNum;
        long start = 0;
        try {
            fileReader = new FileReader(file1);
            fileWriter = new FileWriter(file2, true);
            start = System.currentTimeMillis();
            while ((charsNum = fileReader.read(chars)) != -1) {
                fileWriter.write(chars, 0, charsNum);
                fileWriter.flush();
            }
            System.out.println("复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
            if (fileReader != null) {
                fileReader.close();
            }
            System.out.println(System.currentTimeMillis() - start);
        }
    }

}
